package com.ruoyi.iot.service.impl;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.user.UserException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.iot.domain.Agent;
import com.ruoyi.iot.domain.Dict;
import com.ruoyi.iot.domain.ExtraAgent;
import com.ruoyi.iot.mapper.ExtraAgentMapper;
import com.ruoyi.iot.mapper.IotMapper;
import com.ruoyi.iot.mapper.StatisticDataMapper;
import com.ruoyi.iot.service.IStatisticDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * @ClassName StatisticDateServiceImpl
 * @Description TODO
 * @Author hly
 * @Date 2024/1/17 14:52
 */

@Service
public class StatisticDataServiceImpl implements IStatisticDataService {

    @Autowired
    private IotMapper iotMapper;
    @Autowired
    private ExtraAgentMapper extraAgentMapper;
    @Autowired
    private StatisticDataMapper statisticDataMapper;



    @Override
    public List<Dict> agentDicts(LoginUser user) {

        List<Dict> list = new ArrayList<>();
        List<ExtraAgent> extraAgents = extraAgentMapper.selectExtraAgentByUserId(user.getUserId());
        Agent agent = iotMapper.findAgentByName(user.getUsername());
        if (agent == null) {
            throw new RuntimeException("该用户不是物联卡系统代理用户,无法使用此功能");
        }
        List<Integer> ids = iotMapper.findAgentChilds(agent.getId());
        if (!ids.isEmpty()) {
            List<Agent> maps = iotMapper.getAgentListByIds(ids);
            maps.forEach(x->{
                Dict dict = new Dict();
                dict.setId(x.getId());
                dict.setName(x.getName());
                list.add(dict);
            });
        }

        if (!extraAgents.isEmpty()) {
            extraAgents.forEach(x->{
                Dict dict = new Dict();
                dict.setId(x.getExtraAgentId().intValue());
                dict.setName(x.getExtraAgentName());
                list.add(dict);
            });
        }
        return list;
    }

    @Override
    public List<Dict> channleDicts() {
        return statisticDataMapper.channelDict();
    }

    @Override
    public List<Dict> getDict(String code) {
        return statisticDataMapper.getDict(code);
    }

    @Override
    public List<Dict> packageGroupDict() {
        LoginUser user = getLoginUser();
        System.out.println("user.getUsername()"+user.getUsername());
        if (!user.getUsername().equals("admin")) {
            List<Agent> maps = iotMapper.listAgent(user.getUsername(),"accurate");
            if (maps.isEmpty()) {
                throw new UserNotExistsException();
            }
            return statisticDataMapper.packageGroupDict(maps.get(0).getId());
        }else {
            return statisticDataMapper.packageGroupDict(1);
        }

    }
}
